//
//  EWDatePickerViewController.swift
//  EWDatePicker
//
//  Created by Ethan.Wang on 2018/8/27.
//  Copyright © 2018年 Ethan. All rights reserved.
//

import UIKit

class EWDatePickerViewController: UIView {

    var backDate: ((Date) -> Void)?
    
    lazy var currentDateCom: DateComponents = {
        let dateFormart = DateFormatter.init()
        dateFormart.dateFormat = "yyyy-MM-dd HH:mm"
//        let startCompent = Calendar.current.dateComponents([.year, .month, .day,.hour,.minute], from: Date())
        let starDate = Date()
        let component = Calendar.current.dateComponents([.year, .month, .day,.hour,.minute], from: starDate)
        return component
    }()
    
    
//    private var currentDateCom: DateComponents = Calendar.current.dateComponents([.year, .month, .day],   from:Date.init(timeInterval: 3650*3600, since: Date.dateWithDaysBeforeNow(3650)))
    var containV:UIView = {
        let view = UIView(frame: CGRect(x: 0, y: UIScreen.height-240, width: UIScreen.width, height: 240))
        view.backgroundColor = UIColor.white
        return view
    }()
    var backgroundView:UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        return view
    }()
    var picker: UIPickerView!


    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        self.drawMyView()
    }
    
    
    // MARK: - Func
    private func drawMyView() {
        self.insertSubview(self.backgroundView, at: 0)
        
        let cancel = UIButton(frame: CGRect(x: 0, y: 10, width: 70, height: 20))
        let sure = UIButton(frame: CGRect(x: UIScreen.width - 80, y: 10, width: 70, height: 20))
        cancel.setTitle("取消", for: .normal)
        cancel.titleLabel?.font = .systemFont(ofSize: 15, weight: .medium)
        sure.setTitle("确认", for: .normal)
        sure.titleLabel?.font = .systemFont(ofSize: 15, weight: .medium)
        cancel.setTitleColor(.color_999999, for: .normal)
        sure.setTitleColor(.color_34CE98, for: .normal)
        cancel.addTarget(self, action: #selector(self.onClickCancel), for: .touchUpInside)
        sure.addTarget(self, action: #selector(self.onClickSure), for: .touchUpInside)
        picker = UIPickerView(frame: CGRect(x: 0, y: 24, width: UIScreen.width, height: 216))
        picker.delegate = self
        picker.dataSource = self
        picker.backgroundColor = UIColor.clear
        picker.clipsToBounds = true//如果子视图的范围超出了父视图的边界，那么超出的部分就会被裁剪掉。
        //创建日期选择器
        self.containV.addSubview(cancel)
        self.containV.addSubview(sure)
        self.containV.addSubview(picker)
        self.addSubview(self.containV)
        
        self.containV.addCorner(conrners: [.topLeft,.topRight], radius: 12)

        self.picker.reloadAllComponents()
    }

    // MARK: onClick
    @objc func onClickCancel() {
        self.hide()
    }
    
    func show()  {
        
        UIView.animate(withDuration: 0.2, animations: {
            /// transform初始化
            self.containV.transform = CGAffineTransform.identity
        }, completion: { (_) in
           
        })
    }
    
    func hide()  {
        UIView.animate(withDuration: 0.25, animations: {
            /// datepicker向下推回
            self.containV.transform =  CGAffineTransform(translationX: 0, y: (self.containV.frame.height))
        }) { (_) in
            self.isHidden = true
            self.removeFromSuperview()
        }
    }
    
    @objc func onClickSure() {
       
        let dateString = String(format: "%02ld-%02ld-%02ld %02ld:%02ld", self.picker.selectedRow(inComponent: 0)+self.currentDateCom.year!, self.picker.selectedRow(inComponent: 1) + 1, self.picker.selectedRow(inComponent: 2) + 1,self.picker.selectedRow(inComponent: 3),self.picker.selectedRow(inComponent: 4))
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "YYYY-MM-dd HH:mm"
        /// 直接回调显示
        if self.backDate != nil {
            self.backDate!(dateFormatter.date(from: dateString) ?? Date())
        }
        self.hide()
    }
    ///点击任意位置view消失
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        let currentPoint = touches.first?.location(in: self)
        if !self.containV.frame.contains(currentPoint ?? CGPoint()) {
            self.hide()
        }
    }

  

}
// MARK: - PickerViewDelegate
extension EWDatePickerViewController:UIPickerViewDelegate,UIPickerViewDataSource {
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        var label = view as? UILabel
        if label == nil {
            label = UILabel.init()
            label?.adjustsFontSizeToFitWidth = true
            label?.textAlignment = .center
            label?.backgroundColor = .clear
            label?.font = .systemFont(ofSize: 14, weight: .medium)
        }
        label?.text = self.pickerView(picker, titleForRow: row, forComponent: component)
        return label!
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 5
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return 50
        } else if component == 1 {
            return 12
        } else if component == 2{
         
            let year: Int = pickerView.selectedRow(inComponent: 0)+self.currentDateCom.year!
            let month: Int = pickerView.selectedRow(inComponent: 1) + 1
            let days: Int = howManyDays(inThisYear: year, withMonth: month)
            return days
        }else if component == 3 { // 小时
            return 24
        }else {
            return 60
        }
    }
    private func howManyDays(inThisYear year: Int, withMonth month: Int) -> Int {
        if (month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12) {
            return 31
        }
        if (month == 4) || (month == 6) || (month == 9) || (month == 11) {
            return 30
        }
        if (year % 4 == 1) || (year % 4 == 2) || (year % 4 == 3) {
            return 28
        }
        if year % 400 == 0 {
            return 29
        }
        if year % 100 == 0 {
            return 28
        }
        return 29
    }
    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return UIScreen.width / 5.0
    }
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 40
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if component == 0 {
         
            return "\((self.currentDateCom.year!) + row)\("年")"
        } else if component == 1 {
            return "\(row + 1)\("月")"
        } else if component == 2{
            return "\(row + 1)\("日")"
        }else if component == 3{
            return "\(row)\("时")"
        }else {
            return "\(row)\("分")"
        }
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0 {
            pickerView.reloadComponent(1)
            pickerView.reloadComponent(2)
            pickerView.reloadComponent(3)
            pickerView.reloadComponent(4)
        }
        if component == 1 {
            pickerView.reloadComponent(2)
            pickerView.reloadComponent(3)
            pickerView.reloadComponent(4)
        }
        if component == 2 {
            pickerView.reloadComponent(3)
            pickerView.reloadComponent(4)
        }
        if component == 3 {
            pickerView.reloadComponent(4)
        }
    }
}
